﻿using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

namespace OpenPRS.Controllers
{
    public class UsersController : Controller
    {

        public ActionResult Edit(string name)
        {
            if(name == null)
            {
                return new RedirectToRouteResult(new RouteValueDictionary(
                    new {controller = "Admin", action = "Users"}));
            }
            //TODO: Logic for ensuring the user actually exists before we attempt to edit.  

            return View(Membership.GetUser(name));
        }

        [HttpPost]
        public ActionResult Edit(FormCollection collection)
        {
            var user = Membership.GetUser(collection["oldusername"]);
            //TODO:  Possibility that user was deleted in interim; check for null here.  
            //TODO:  Check for password policy violations.  
            user.ChangePassword(user.ResetPassword(), collection["password"]);
            user.Email = collection["Email"];
            return new RedirectToRouteResult(new RouteValueDictionary(
                    new { controller = "Admin", action = "Users" }));
        }

        public ActionResult Delete(string name)
        {
            if(name==null)
            {
                return new RedirectToRouteResult(new RouteValueDictionary(
                    new { controller = "Admin", action = "Users" }));
            }
            //TODO:  Logic for ensuring the user actually exists before we attempt to delete.  

            return View(Membership.GetUser(name));
        }

        [HttpPost]
        public ActionResult Delete(FormCollection formCollection)
        {
            //TODO: Verify that the user can be deleted.  
            var username = formCollection["usernametodelete"];
            Membership.DeleteUser(username);
            return new RedirectToRouteResult(new RouteValueDictionary(
                new {controller = "Admin", action = "Users"}));
        }
    }
}
